import paramiko
import os
from base64 import *
import platform
"""
或vim编辑器写文件，但是遇到了一个问题："Output is not to a terminal"。

原因解释：
Paramiko是一个Python库，它允许你通过SSH协议进行连接和交互。当你尝试在没有分配到终端的环境中运行vim或者其他需要在终端中运行的命令时，就会出现这个问题。
解决方法：
1、使用ssh命令直接在终端中运行vim，而不是通过paramiko的exec_command方法。
2、如果你需要通过paramiko自动化编辑文件，可以考虑使用paramiko的send和recv方法来读取和写入文件内容，或者使用scp来复制文件到远端服务器进行编辑，编辑完成后再复制回来。
3、另一个选择是使用一个能够通过SSH直接在远端执行编辑操作的编辑器，例如sed或nano，这些编辑器不需要终端
"""

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())


def system_info():
    # 获取操作系统信息
    os_info = platform.platform()
    # 打印操作系统信息
    print(f"操作系统信息: {os_info}")


def generate_cmd_file(tmp_file_content):
    stdin, stdout, stderr = client.exec_command(command=f"echo '{tmp_file_content}' > ~/tmp.py", timeout=10000)
    return stderr


def generate_cmd_file2(tmp_file_content):
    stdin, stdout, stderr = client.exec_command(command="vi ~/tmp.py", get_pty=False, timeout=10000)
    stdin.write('i\n')  # 按 'i' 进入插入模式
    stdin.write(tmp_file_content)
    stdin.write('esc\n')  # 按 'esc' 退出插入模式
    stdin.write(':wq\n')  # 输入 ':wq'
    stdin.flush()
    return stderr


def generate_cmd_file3(tmp_file_content):
    stdin, stdout, stderr = client.exec_command(command="nano ~/tmp.py", get_pty=False, timeout=10000)
    #stdin.write(tmp_file_content)

    stdin.write("\x0f")
    stdin.write("\n"*5)
    stdin.write("\x18")

    return stderr


def generate_cmd_file4(tmp_file_content):
    # 将本地文件内容写入远程服务器的文件
    # local_file_path = '/path/to/local/file'
    remote_file_path = '/home/fred/tmp.py'
    transport = paramiko.Transport(("192.168.88.89", 22))
    transport.connect(username="fred", password="123")
    sftp = paramiko.SFTPClient.from_transport(transport)
    with sftp.open(remote_file_path, 'w') as remote_file:
        #with open(local_file_path, 'r') as local_file:
            remote_file.write(tmp_file_content)


def connect(self: paramiko.SSHClient, hostname, port=22, username=None, password=None, *args, **kwargs):
    print(args, kwargs)
    print(*args, **kwargs)
    return self.connect(hostname, port, username, password, *tuple(args), **dict(kwargs))




tmp_file_content = """# coding: utf-8
import base64 as b64
import traceback
import os

# 不需要while,input()会形成等待；加了while会死循环，没有结束命令flush out stdout的机会 
while 1:
    command = input()
    command = command.split(", ")
    # print("helloWorld")
    with open("/tmp/filename.log", "wb") as f:
        f.write(f"test:\\n".encode("utf-8"))
        f.write(f"{command[0]}\\n".encode("utf-8")) 
        f.write(f"{command[1]}\\n".encode("utf-8")) 
    try:
        filename = b64.b64decode(command[1].encode("utf-8")).decode("utf-8")
        home_directory = os.path.expanduser("~")
        filename = filename.replace("~",home_directory)
        with open("/tmp/filename_error.log", "wb") as f:
            f.write(f"filename: {filename}\\n".encode("utf-8"))
        if command[0] == "write":
            file_content = b64.b64decode(command[2].encode("utf-8"))
            f = open(filename, "wb")
            f.write(file_content)
            f.close()
        elif command[0] == "read":
            f = open(filename, "rb")
            file_content = f.read()
            f.close()
            with open("/tmp/filename_content.log", "wb") as f:
                f.write(f"file_content: {file_content}\\n".encode("utf-8"))
            file_content = b64.b64encode(file_content).decode("utf-8")
            print(file_content)
        else:
            print(filename)
        exit(0)
    except Exception as e:
        error_msg = "".join(traceback.format_exception_only(type(e), e))
        print(error_msg)
        with open("/tmp/filename_error.log", "wb") as f:
            f.write(f"error: {error_msg}\\n".encode("utf-8"))
        print(e)
"""



def readfile(filename:str):
    print("reading...")
    stdin, stdout, stderr = client.exec_command(
        command="sudo python3 ~/tmp.py",
        timeout=10000
    )
    print("reading2...")


    command = f"read, {b64encode(filename.encode('utf-8')).decode('utf-8')}\n"
    print(command)
    stdin.write(command)
    if stderr.read():
        print(stderr.read())
        exit(1)
    result = stdout.read()
    print("stdout", result)
    return b64decode(result).decode("utf-8")


def writefile(filename, content):
    stdin, stdout, stderr = client.exec_command(
        command="sudo python3 ~/tmp.py",
        timeout=10000
    )
    if isinstance(content, str):
        content = content.encode("utf-8")
        command = f"write, {b64encode(filename.encode('utf-8')).decode('utf-8')}, {b64encode(content).decode('utf-8')}\n"
        print(command)
        stdin.write(command)
    if stderr.read():
        print(stderr.read())
        exit(1)
    return b64decode(stdout.read())


def send_cmd(cmd: str):
    stdin, stdout, stderr = client.exec_command(
        command=cmd,
        timeout=100
    )
    print(stdout.read().decode("utf-8"))
    exit(0)


def test_args(*args, **kwargs):
    print(args, kwargs)
    print(kwargs['name'])
    # print(*args, **kwargs)  #报错
    return test_args2(*args, **kwargs)

def test_args2(*args, **kwargs):
    print(args, kwargs)


if __name__ == '__main__':
    print("begin...")
    # client.connect("192.168.88.89", 22, username="fred", password="123", timeout=10000)
    # stderr = generate_cmd_file(tmp_file_content)
    # if stderr.read():
    #     print(stderr.read())
    #     exit(1)

    #print(readfile("/home/fred/test.txt"))
    #send_cmd("cat /proc/version")
    #writefile("/tmp/test2.log", "son of bitch,bitch")
    # test_args(1, 2, name="tony", age=43)
    print("shit")
    print(os.name)
    system_info()